<script setup lang="ts">
// @ts-nocheck
import { ref, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { showToast, showLoadingToast, closeToast, showSuccessToast } from 'vant';
import axios from 'axios';
// 添加优惠券相关导入
import { loadUserCoupons, getAvailableCoupons, useCoupon, type Coupon } from '@/utils/couponStore';
const route = useRoute();
const router = useRouter();

// 订单数据
interface OrderItem {
  id: number;
  name: string;
  price: number;
  image: string;
  quantity: number;
  selected: boolean;
}

const orderItems = ref<OrderItem[]>([]);
const totalPrice = ref(0);
const totalCount = ref(0);

// 优惠券相关状态
const availableCoupons = ref<Coupon[]>([]);
const selectedCoupon = ref<Coupon | null>(null);
const showCouponSelector = ref(false);

// 运费
// 运费
const shippingFee = ref(17.00);

// 支付方式
const paymentMethod = ref('alipay');

// 合并计算属性
const orderCalculations = computed(() => {
  const couponDiscount = selectedCoupon.value?.amount || 0
  const needsShipping = totalCount.value >= 2
  const shippingCost = needsShipping ? shippingFee.value : 0
  const finalAmount = Math.max(0, totalPrice.value - couponDiscount + shippingCost)

  return {
    couponDiscount,
    needsShipping,
    shippingCost,
    finalAmount,
    hasCoupon: !!selectedCoupon.value,
    isFreeShipping: totalCount.value < 2
  }
})

// 简化优惠券管理
const couponManager = {
  load: () => {
    loadUserCoupons()
    availableCoupons.value = getAvailableCoupons(totalPrice.value)
    if (selectedCoupon.value && !availableCoupons.value.find(c => c.id === selectedCoupon.value?.id)) {
      selectedCoupon.value = null
    }
  },
  select: (coupon: Coupon | null) => {
    selectedCoupon.value = coupon
    showCouponSelector.value = false
  },
  toggle: () => {
    couponManager.load()
    showCouponSelector.value = true
  }
}

// 返回上一页
const goBack = () => {
  router.back();
};

// 提交订单并跳转支付宝沙箱支付（纯前端版本）
const submitOrder = async () => {
  if (orderCalculations.value.finalAmount <= 0) {
    showToast('订单金额异常');
    return;
  }

  showLoadingToast({
    message: '正在创建订单...',
    forbidClick: true,
    duration: 0
  });

  try {
    // 验证订单数据
    if (!orderItems.value || orderItems.value.length === 0) {
      throw new Error('购物车为空');
    }

    if (orderCalculations.value.finalAmount <= 0) {
      throw new Error('订单金额异常');
    }

    // 创建订单数据，包含优惠券信息
    const orderData = {
      orderId: 'ORDER_' + Date.now(),
      amount: orderCalculations.value.finalAmount.toFixed(2),
      subject: `运动商城订单-${orderItems.value.length}件商品`,
      body: orderItems.value.map(item => item.name).join(', '),
      couponId: selectedCoupon.value?.id
    };

    // 调用后端创建支付订单
    const response = await axios.post('http://localhost:3000/api/alipay/create', orderData);

    if (response.data.code === 200) {
      closeToast();

      showToast({
        message: '正在跳转到支付宝...',
        duration: 1500
      });

      setTimeout(() => {
        const paymentForm = response.data.data.paymentUrl;
        const newWindow = window.open('', '_self');
        newWindow.document.write(paymentForm);
        newWindow.document.close();
      }, 1500);
    } else {
      throw new Error(response.data.msg || '创建支付订单失败');
    }

  } catch (error) {
    closeToast();
    console.error('创建订单失败:', error);
    const errorMessage = error instanceof Error ? error.message : '创建订单失败，请重试';
    showToast(errorMessage);
  }
};

// 修改支付成功处理逻辑
onMounted(() => {
  const paymentStatus = route.query.status;
  const couponId = route.query.couponId;

  if (paymentStatus === 'success') {
    console.log('检测到支付成功回调');

    if (couponId) {
      const success = useCoupon(couponId as string);
      if (success) {
        console.log('优惠券使用成功');
      }
    }

    showSuccessToast('支付成功！订单已完成');
    localStorage.removeItem('cartItems');
    console.log('购物车已清空');

    setTimeout(() => {
      console.log('准备跳转到商城页面');
      router.push('/shop');
    }, 3000);
    return;
  }

  try {
    // 从localStorage获取数据而不是URL参数
    const checkoutDataStr = localStorage.getItem('checkoutData');
    if (!checkoutDataStr) {
      throw new Error('没有结算数据');
    }

    const data = JSON.parse(checkoutDataStr);
    orderItems.value = data.items;
    totalPrice.value = data.totalPrice;
    totalCount.value = orderItems.value.reduce((total, item) => total + item.quantity, 0);

    if (data.selectedCoupon) {
      selectedCoupon.value = data.selectedCoupon;
    }

    couponManager.load();
  } catch (error) {
    showToast('订单数据异常');
    router.back();
  }
});
</script>

<template>
  <div class="checkout-container">
    <!-- 头部导航 -->
    <van-nav-bar title="确认订单" left-arrow @click-left="goBack" class="checkout-header" />

    <div class="checkout-content">
      <!-- 商品列表 -->
      <div class="section">
        <div class="section-title">商品</div>
        <div class="product-list">
          <div v-for="item in orderItems" :key="item.id" class="product-item">
            <img :src="item.image" :alt="item.name" class="product-image" />
            <div class="product-info">
              <div class="product-name">{{ item.name }}</div>
              <div class="product-desc">规格：默认规格</div>
              <div class="product-tag">7天无理由退货</div>
            </div>
            <div class="product-right">
              <div class="product-price">¥{{ item.price.toFixed(2) }}</div>
              <div class="product-quantity">{{ item.quantity }}</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 商品总价 -->
      <div class="section">
        <div class="price-row">
          <span>商品总价</span>
          <span class="price">¥{{ totalPrice.toFixed(2) }}</span>
        </div>
      </div>

      <!-- 优惠券 -->
      <div class="section">
        <div class="coupon-row">
          <div class="coupon-left">
            <van-icon name="coupon" color="#52c41a" />
            <span class="coupon-text">优惠券</span>
          </div>
          <div class="coupon-right">
            <span class="coupon-status" :class="{ active: orderCalculations.hasCoupon }">{{ orderCalculations.hasCoupon
              ? '省' : '' }}</span>
            <span class="coupon-amount" :class="{ active: orderCalculations.hasCoupon }">
              {{ selectedCoupon ? `¥${selectedCoupon.amount.toFixed(2)}` : '选择优惠券' }}
            </span>
            <van-icon name="arrow" />
          </div>
        </div>
        <div class="coupon-desc">
          {{ selectedCoupon ? selectedCoupon.description : '点击选择可用优惠券' }}
        </div>
      </div>

      <!-- 优惠券选择弹窗 -->
      <van-popup v-model:show="showCouponSelector" position="bottom" :style="{ height: '60%' }" round>
        <div class="coupon-selector">
          <div class="selector-header">
            <h3>选择优惠券</h3>
            <span class="available-count">{{ availableCoupons.length }}张可用</span>
          </div>

          <div class="selector-content">
            <div class="coupon-option" @click="couponManager.select(null)">
              <div class="option-left">
                <van-icon name="circle" :color="!selectedCoupon ? '#4CAF50' : '#ddd'" />
                <span>不使用优惠券</span>
              </div>
            </div>

            <div v-for="coupon in availableCoupons" :key="coupon.id" class="coupon-option"
              @click="couponManager.select(coupon)">
              <div class="option-left">
                <van-icon name="circle" :color="selectedCoupon?.id === coupon.id ? '#4CAF50' : '#ddd'" />
                <div class="coupon-info">
                  <div class="coupon-name">{{ coupon.name }}</div>
                  <div class="coupon-desc">{{ coupon.description }}</div>
                </div>
              </div>
              <div class="coupon-value">¥{{ coupon.amount.toFixed(2) }}</div>
            </div>

            <div v-if="availableCoupons.length === 0" class="no-coupon">
              <p>暂无可用优惠券</p>
              <p>去我的页面查看更多优惠券</p>
            </div>
          </div>
        </div>
      </van-popup>

      <!-- 运动福利 -->
      <div class="section">
        <div class="benefit-row">
          <div class="benefit-left">
            <van-icon name="gift" color="#ff6b35" />
            <span>运动福利</span>
          </div>
          <span class="benefit-status">不可用</span>
        </div>
      </div>

      <!-- 运费 -->
      <!-- 运费 -->
      <!-- 运费 -->
      <!-- 运费 -->
      <div class="section">
        <div class="shipping-header">
          <span>运费</span>
          <span class="shipping-type">{{ orderCalculations.isFreeShipping ? '免运费' : '需要运费' }}</span>
        </div>
        <div class="shipping-info">
          <van-icon name="location" />
          <span class="shipping-text">{{ orderCalculations.isFreeShipping ? '单件商品免运费' : '两件以上收取运费' }}</span>
          <van-icon name="info" />
        </div>
        <div class="shipping-detail">
          <span>共{{ totalCount }}件小计</span>
          <span class="shipping-fee">¥{{ orderCalculations.isFreeShipping ? '0.00' : shippingFee.toFixed(2) }}</span>
        </div>
      </div>

      <!-- 退换无忧服务 -->
      <div class="section">
        <div class="service-row">
          <span>退换无忧服务</span>
          <van-icon name="info" />
        </div>
        <div class="service-desc">
          上门取件内容易损，自行寄回商品满7天可享受12元
        </div>
        <div class="service-option">
          <span class="service-label">素颜嗨送</span>
        </div>
      </div>

      <!-- 运动节热扣 -->
      <div class="section">
        <div class="activity-row">
          <van-icon name="fire" color="#ff6b35" />
          <span>使用运动节热扣</span>
          <span class="activity-status">无可用</span>
        </div>
      </div>

      <!-- 红包抵扣 -->
      <div class="section">
        <div class="redpack-row">
          <van-icon name="gift" color="#f5222d" />
          <span>使用红包抵扣</span>
          <span class="redpack-status">无可用</span>
        </div>
      </div>
    </div>

    <!-- 底部结算栏 -->
    <div class="checkout-footer">
      <div class="total-info">
        <div class="total-row">
          <span class="total-label">实际支付</span>
          <span class="total-price">¥{{ orderCalculations.finalAmount.toFixed(2) }}</span>
        </div>
        <div class="discount-info">
          已优惠 ¥{{ orderCalculations.couponDiscount.toFixed(2) }}，免运费节省 ¥{{ orderCalculations.isFreeShipping ?
            shippingFee.toFixed(2) : '0.00' }}
        </div>
      </div>
      <van-button type="primary" size="large" @click="submitOrder" class="submit-btn">
        {{ orderCalculations.finalAmount.toFixed(0) }}元下单
      </van-button>
    </div>
  </div>
</template>

<style scoped>
.checkout-container {
  min-height: 100vh;
  background-color: #f7f8fa;
  padding-bottom: 80px;
}

.checkout-header {
  background-color: #fff;
  border-bottom: 1px solid #eee;
}

.checkout-content {
  padding: 0;
}

.section {
  background-color: #fff;
  margin-bottom: 8px;
  padding: 16px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 12px;
  color: #333;
}

/* 商品列表样式 */
.product-item {
  display: flex;
  align-items: flex-start;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.product-item:last-child {
  border-bottom: none;
}

.product-image {
  width: 60px;
  height: 60px;
  border-radius: 4px;
  margin-right: 12px;
}

.product-info {
  flex: 1;
}

.product-name {
  font-size: 14px;
  color: #333;
  margin-bottom: 4px;
}

.product-desc {
  font-size: 12px;
  color: #999;
  margin-bottom: 4px;
}

.product-tag {
  font-size: 12px;
  color: #f5222d;
}

.product-right {
  text-align: right;
}

.product-price {
  font-size: 16px;
  color: #333;
  font-weight: bold;
  margin-bottom: 4px;
}

.product-quantity {
  font-size: 14px;
  color: #999;
}

/* 价格行样式 */
.price-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.price {
  font-size: 16px;
  color: #333;
  font-weight: bold;
}

/* 优惠券样式 */
.coupon-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.coupon-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.coupon-text {
  font-size: 14px;
  color: #333;
}

.coupon-right {
  display: flex;
  align-items: center;
  gap: 4px;
}

.coupon-status {
  background-color: #f0f0f0;
  color: #999;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
}

.coupon-status.active {
  background-color: #52c41a;
  color: #fff;
}

.coupon-amount {
  color: #999;
  font-size: 14px;
}

.coupon-amount.active {
  color: #52c41a;
  font-weight: bold;
}

.coupon-desc {
  font-size: 12px;
  color: #999;
  line-height: 1.4;
}

/* 福利行样式 */
.benefit-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.benefit-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.benefit-status {
  color: #999;
  font-size: 14px;
}

/* 运费样式 */
.shipping-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.shipping-type {
  background-color: #52c41a;
  color: #fff;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.shipping-info {
  display: flex;
  align-items: center;
  gap: 4px;
  margin-bottom: 8px;
}

.shipping-text {
  font-size: 12px;
  color: #666;
}

.shipping-detail {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
}

.shipping-fee {
  color: #333;
  font-weight: bold;
}

/* 服务样式 */
.service-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.service-desc {
  font-size: 12px;
  color: #999;
  line-height: 1.4;
  margin-bottom: 8px;
}

.service-option {
  display: flex;
  align-items: center;
}

.service-label {
  background-color: #f0f0f0;
  color: #666;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

/* 活动样式 */
.activity-row,
.redpack-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 8px;
}

.activity-status,
.redpack-status {
  color: #999;
  font-size: 14px;
}

/* 底部结算栏 */
.checkout-footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 16px;
  border-top: 1px solid #eee;
  display: flex;
  align-items: center;
  gap: 16px;
}

.total-info {
  flex: 1;
}

.total-row {
  display: flex;
  align-items: baseline;
  gap: 8px;
  margin-bottom: 4px;
}

.total-label {
  font-size: 14px;
  color: #333;
}

.total-price {
  font-size: 18px;
  color: #f5222d;
  font-weight: bold;
}

.discount-info {
  font-size: 12px;
  color: #999;
}

.submit-btn {
  background: linear-gradient(135deg, #52c41a, #389e0d);
  border: none;
  border-radius: 24px;
  min-width: 120px;
  font-weight: bold;
}

/* 优惠券选择器样式 */
.coupon-selector {
  max-height: 60vh;
  overflow-y: auto;
}

.coupon-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #eee;
}

.coupon-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.coupon-list {
  padding: 16px;
}

.coupon-item {
  display: flex;
  align-items: center;
  padding: 16px;
  margin-bottom: 12px;
  background-color: #f8f9fa;
  border-radius: 8px;
  border: 2px solid transparent;
  cursor: pointer;
  transition: all 0.3s ease;
}

.coupon-item.selected {
  border-color: #52c41a;
  background-color: #f6ffed;
}

.coupon-content {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 12px;
}

.coupon-amount-large {
  font-size: 24px;
  font-weight: bold;
  color: #f5222d;
  min-width: 60px;
}

.coupon-info {
  flex: 1;
}

.coupon-name {
  font-size: 14px;
  color: #333;
  margin-bottom: 4px;
}

.coupon-condition {
  font-size: 12px;
  color: #666;
  margin-bottom: 2px;
}

.coupon-expire {
  font-size: 12px;
  color: #999;
}
</style>
